﻿namespace Digitalmes.Application.Sys.Dicts.Commands;

/// <summary>
/// 创建字典命令。
/// </summary>
/// <param name="Dict"></param>
public record CreateDictCommand(SysDictDto Dict) : IRequest<IResult<bool>>;

internal sealed class CreateDictCommandHandler(IRepository<SysDict> repo) : IRequestHandler<CreateDictCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(CreateDictCommand request, CancellationToken cancellationToken)
    {
        // 检查字典是否已存在。
        if (await repo.IsAnyAsync(m => m.Code == request.Dict.Code, cancellationToken))
        {
            return Result.Failure("字典编号已存在");
        }

        var dict = request.Dict.Adapt<SysDict>();
        var ok = await repo.InsertAsync(dict, cancellationToken);
        return Result.From(ok);
    }
}
